package com.nft.service.school.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nft.constant.response.ResponseConstants;
import com.nft.paging.Paginator;
import com.nft.po.NftResponse;
import com.nft.service.school.dto.BookContentDto;
import com.nft.service.school.dto.BookDetailDto;
import com.nft.service.school.dto.BookQuestionDto;
import com.nft.service.school.entity.*;
import com.nft.service.school.mapper.*;
import com.nft.service.school.req.BookReq;
import com.nft.service.school.req.SysUserReq;
import com.nft.service.school.req.UserBookReq;
import com.nft.service.school.resp.*;
import com.nft.service.school.service.AuthService;
import com.nft.service.school.service.BookManagerService;
import com.nft.service.school.util.Base64Util;
import com.nft.service.school.util.ParsePdfContent;
import com.nft.service.school.util.Tess4jClient;
import com.nft.utils.dateFormat.SimpleDateFormatUtil;
import com.nft.utils.query.QueryUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Service
public class BookManagerServiceImpl extends ServiceImpl<BookMapper, BookEntity> implements BookManagerService {
    @Resource
    private StringRedisTemplate myRedisTemplate;
    @Autowired
    private BookContentMapper bookContentMapper;
    @Autowired
    private UserBooksMapper userBooksMapper;
    @Autowired
    private SchoolClassesMapper schoolClassesMapper;
    @Autowired
    private SchoolStudentMapper schoolStudentMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private UserBooksDetailMapper userBooksDetailMapper;
    @Autowired
    private Tess4jClient tess4jClient;
    @Autowired
    private AuthService authService;

    @Override
    public NftResponse<List<String>> getGrade() {
        Map<Object, Object> mapValue = myRedisTemplate.opsForHash().entries("GRADE");
        List<String> listResult = new ArrayList<>();
        if (mapValue.isEmpty()) {
            List<BookContentResp> dictList = this.baseMapper.selectDictByType("grade");
            mapValue = new HashMap<>();
            for (BookContentResp obj:dictList) {
                mapValue.put(obj.getDictCode(), obj.getDictValue());
                listResult.add(obj.getDictValue());
            }
            myRedisTemplate.opsForHash().putAll("GRADE", mapValue);
        }else {
            for (Map.Entry<Object, Object> entry : mapValue.entrySet()) {
                listResult.add(entry.getValue().toString());
            }
        }
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "获取成功", listResult);
    }

    @Override
    public NftResponse<List<String>> getSubject() {
        Map<Object, Object> mapValue = myRedisTemplate.opsForHash().entries("SUBJECT");
        List<String> listResult = new ArrayList<>();
        if (mapValue.isEmpty()) {
            List<BookContentResp> dictList = this.baseMapper.selectDictByType("subject");
            mapValue = new HashMap<>();
            for (BookContentResp obj:dictList) {
                mapValue.put(obj.getDictCode(), obj.getDictValue());
                listResult.add(obj.getDictValue());
            }
            myRedisTemplate.opsForHash().putAll("SUBJECT", mapValue);
        }else {
            for (Map.Entry<Object, Object> entry : mapValue.entrySet()) {
                listResult.add(entry.getValue().toString());
            }
        }
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "获取成功", listResult);
    }

    @Override
    public NftResponse<List<String>> getDispart() {
        Map<Object, Object> mapValue = myRedisTemplate.opsForHash().entries("DISPART");
        List<String> listResult = new ArrayList<>();
        if (mapValue.isEmpty()) {
            List<BookContentResp> dictList = this.baseMapper.selectDictByType("dispart");
            mapValue = new HashMap<>();
            for (BookContentResp obj:dictList) {
                mapValue.put(obj.getDictCode(), obj.getDictValue());
                listResult.add(obj.getDictValue());
            }
            myRedisTemplate.opsForHash().putAll("DISPART", mapValue);
        }else {
            for (Map.Entry<Object, Object> entry : mapValue.entrySet()) {
                listResult.add(entry.getValue().toString());
            }
        }
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "获取成功", listResult);
    }

    @Override
    public NftResponse<Paginator<BookResp>> getBookList(BookReq query) {
        Paginator<BookResp> paginator = new Paginator<BookResp>(query.getPageNo(), query.getPageSize(), 0, new ArrayList<>());
        QueryWrapper<BookEntity> wrapperQuery = new QueryWrapper<>();
        wrapperQuery.orderByDesc("create_time");
        Page<BookEntity> resultPage = this.baseMapper.selectPage(new Page<>(query.getPageNo(),query.getPageSize()),wrapperQuery);
        List<BookResp> pageResult = BeanUtil.copyToList(resultPage.getRecords(), BookResp.class);
        List<Long> idList = new ArrayList<>();
        HashMap<Long, Date> SjTimeMap = new HashMap<>();
        HashMap<Long, Long> UserBIdMap = new HashMap<>();
        if (null!=query.getUserId()&&query.getUserId()>0) {
            List<BookResp> list = userBooksMapper.getBookInfoListByUserId(query.getUserId());
            for (BookResp item:list) {
                idList.add(item.getId());
                SjTimeMap.put(item.getId(),item.getSjTime());
                UserBIdMap.put(item.getId(),item.getUserbookId());
            }
        }
        for (BookResp obj : pageResult) {
            boolean searchTitle = false;
            boolean searchGrade = false;
            boolean searchSubject = false;
            boolean searchDispart = false;
            if ((null!=query.getTitle()&&obj.getTitle().indexOf(query.getTitle())>=0)||
                null==query.getTitle()||"".equals(query.getTitle())) {
                searchTitle = true;
            }
            if ((null!=query.getGrade()&&query.getGrade().equals(obj.getGrade()))||
                null==query.getGrade()||"".equals(query.getGrade())) {
                searchGrade = true;
            }
            if ((null!=query.getSubject()&&query.getSubject().equals(obj.getSubject()))||
                null==query.getSubject()||"".equals(query.getSubject())) {
                searchSubject = true;
            }
            if ((null!=query.getDispart()&&query.getDispart().equals(obj.getDispart()))||
                null==query.getDispart()||"".equals(query.getDispart())) {
                searchDispart = true;
            }
            if (searchTitle&&searchGrade&&searchSubject&&searchDispart) {
                List<BookContentResp> bookContentList = this.getContentList(obj.getId());
                if (null!=bookContentList) {
                    BookContentResp contentResp = bookContentList.get(0);
                    obj.setBookCover("http://timeadmin.shudingkj.com/prod-api"+contentResp.getFileUrl());
                }
                if (null!=query.getUserId()&&query.getUserId()>0) {
                    if (idList.contains(obj.getId())) {
                        obj.setIsSj(true);
                        obj.setSjTime(SjTimeMap.get(obj.getId()));
                        obj.setUserbookId(UserBIdMap.get(obj.getId()));
                    }else {
                        obj.setIsSj(false);
                    }
                }else {
                    obj.setIsSj(false);
                }
            }
        }
        paginator.setPageNo(resultPage.getCurrent());
        paginator.setPageSize(resultPage.getSize());
        paginator.setTotalDataNum(resultPage.getTotal());
        paginator.setPageData(pageResult);
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "获取成功", paginator);
    }

    @Override
    public NftResponse<BookResp> getBookInfoById(Long id) {
        Map<Object, Object> mapValue = myRedisTemplate.opsForHash().entries("BOOK:DATA:"+id);
        BookResp bookResp = null;
        if (mapValue.isEmpty()) {
            BookEntity bookInfo = this.baseMapper.selectById(id);
            mapValue = new HashMap<>();
            mapValue.put(bookInfo.getId()+"", JSON.toJSONString(bookInfo));
            bookResp = BeanUtil.copyProperties(bookInfo, BookResp.class);
            myRedisTemplate.opsForHash().putAll("BOOK:DATA:"+id, mapValue);
        }else {
            for (Map.Entry<Object, Object> entry : mapValue.entrySet()) {
                BookEntity entity = JSON.parseObject(entry.getValue().toString(), BookEntity.class);
                bookResp = BeanUtil.copyProperties(entity, BookResp.class);
            }
        }
        if (bookResp == null) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "查无此图书", null);
        }
        List<BookContentResp> bookContentList = this.getContentList(bookResp.getId());
        if (null!=bookContentList) {
            BookContentResp contentResp = bookContentList.get(0);
            bookResp.setBookCover("http://timeadmin.shudingkj.com/prod-api"+contentResp.getFileUrl());
        }
        return new NftResponse<BookResp>(ResponseConstants.SUCCESS_CODE, "查询成功", bookResp);
    }

    private BookContentEntity getBook(Long taskId) {
        BookContentEntity book = null;
        Map<Object, Object> mapValue = myRedisTemplate.opsForHash().entries("BOOK:DATAD:"+taskId);
        if (!mapValue.isEmpty()) {
            book = JSON.parseObject(taskId+"", BookContentEntity.class);
        }else {
            QueryWrapper<BookContentEntity> wrapperQuery = new QueryWrapper<>();
            wrapperQuery.eq(QueryUtil.camelToUnderline("taskId"), taskId);
            wrapperQuery.eq(QueryUtil.camelToUnderline("type"),"0");
            List<BookContentEntity> bookList = bookContentMapper.selectList(wrapperQuery);
            if (null!=bookList&&bookList.size()>0) {
                mapValue = new HashMap<>();
                mapValue.put(taskId+"", JSON.toJSONString(bookList.get(0)));
                myRedisTemplate.opsForHash().putAll("BOOK:DATAD:", mapValue);
            }
        }
        return book;
    }

    private List<BookContentResp> getContentList(Long taskId) {
        List<BookContentResp> bookContentList = null;
        Map<Object, Object> mapCValue = myRedisTemplate.opsForHash().entries("BOOK:DATADC:"+taskId);
        if (!mapCValue.isEmpty()) {
            bookContentList = JSON.parseArray(mapCValue.get("ALL").toString(), BookContentResp.class);
        }else {
            bookContentList = bookContentMapper.selectContentListByTaskId(taskId);
            mapCValue = new HashMap<>();
            mapCValue.put("ALL", JSON.toJSONString(bookContentList));
            myRedisTemplate.opsForHash().putAll("BOOK:DATADC:", mapCValue);
        }
        return bookContentList;
    }

    private List<BookQuestionDto> getContentDList(Long contentId) {
        List<BookQuestionDto> bookContentDList = null;
        Map<Object, Object> mapDValue = myRedisTemplate.opsForHash().entries("BOOK:DATADD:"+contentId);
        if (!mapDValue.isEmpty()) {
            bookContentDList = JSON.parseArray(mapDValue.get("ALL").toString(), BookQuestionDto.class);
        }else {
            List<BookContentResp> questionList = bookContentMapper.selectContentDListByTaskId(contentId);
            bookContentDList = new ArrayList<>();
            for (BookContentResp obj:questionList) {
                if (null!=obj.getId()) {
                    BookQuestionDto item = new BookQuestionDto();
                    item.setId(obj.getId());
                    item.setUrl("http://timeadmin.shudingkj.com/prod-api" + obj.getFileUrl());
                    item.setContent(obj.getJxfileurl());
                    item.setQuestionNum(obj.getQno());
                    bookContentDList.add(item);
                }
            }
            mapDValue = new HashMap<>();
            mapDValue.put("ALL", JSON.toJSONString(bookContentDList));
            myRedisTemplate.opsForHash().putAll("BOOK:DATADD:", mapDValue);
        }
        return bookContentDList;
    }

    @Override
    public NftResponse<List<BookDetailDto>> getBookDetailInfoById(Long id) {
        Map<Object, Object> mapValue = myRedisTemplate.opsForHash().entries("BOOK:DATAJX:"+id);
        List<BookDetailDto> records = new ArrayList<>();
        int pageNum = 1;
        String jxkey = null;
        if (!mapValue.isEmpty()) {
            List<BookContentDto> contentRtnList = JSON.parseArray(mapValue.get("ALL").toString(), BookContentDto.class);
            if (null!=contentRtnList&&contentRtnList.size()>0) {
                jxkey = contentRtnList.get(0).getJxkey();
            }
        }else {
            BookContentEntity book = this.getBook(id);
            if (null!=book) {
                jxkey = book.getJxkey();
            }
        }
        List<BookContentResp> bookContentList = this.getContentList(id);
        for (BookContentResp obj:bookContentList) {
            List<BookQuestionDto> bookContentDList = this.getContentDList(obj.getId());
            BookDetailDto item = new BookDetailDto();
            item.setId(obj.getId());
            if (null!=obj.getJxfileurl()&&!"".equals(obj.getJxfileurl())) {
                String[] contentAry = obj.getJxfileurl().split(jxkey);
                item.setTitle(contentAry[0]);
            }else {
                item.setTitle(obj.getJxfileurl());
            }
            item.setUrl("http://timeadmin.shudingkj.com/prod-api" + obj.getFileUrl());
            item.setPageNum(pageNum+"");
            item.setDetailList(bookContentDList);
            records.add(item);
            pageNum++;
        }
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "查询成功", records);
    }

    @Override
    public NftResponse<List<BookContentDto>> getBookDetailJxInfoById(Long id, String jxkey) {
        List<BookContentDto> contentRtnList = new ArrayList<>();
        Map<Object, Object> mapValue = myRedisTemplate.opsForHash().entries("BOOK:DATAJX:"+id);
        if (mapValue.isEmpty()) {
            BookContentEntity book = this.getBook(id);
            mapValue = new HashMap<>();
            if (null!=book) {
                String jxkeyD = book.getJxkey();
                String txtStr = ParsePdfContent.reader(book.getJxfileurl());
                if (!"".equals(txtStr)) {
                    String[] jxkeyAry = jxkey.split(";");
                    if (jxkeyAry.length>1) {
                        List<String> titleList = ParsePdfContent.processTitle(txtStr, jxkeyAry[0]);
                        String pdfFileName = book.getJxfileurl().replaceAll(".txt", ".pdf");
                        File file = new File(pdfFileName);
                        contentRtnList = ParsePdfContent.processContent(file, titleList, txtStr, jxkeyAry[1], jxkeyD);
                    }else {
                        String[] jxkeySAry = jxkey.split(",");
                        if (jxkeySAry.length>1) {
                            String pdfFileName = book.getJxfileurl().replaceAll(".txt", ".pdf");
                            File file = new File(pdfFileName);
                            contentRtnList = ParsePdfContent.processSubTitle1(file, txtStr, jxkeySAry[0], jxkeyD);
                            List<BookContentDto> contentRtnListN = ParsePdfContent.processSubTitle2(file, txtStr, jxkeySAry[1], jxkeyD);
                            contentRtnList.addAll(contentRtnListN);
                        }
                    }
                    mapValue.put("ALL", JSON.toJSONString(contentRtnList));
                    myRedisTemplate.opsForHash().putAll("BOOK:DATAJX:"+id, mapValue);
                }
            }
        }else {
            contentRtnList = JSON.parseArray(mapValue.get("ALL").toString(), BookContentDto.class);
        }
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "查询成功", contentRtnList);
    }

    @Override
    public NftResponse<Boolean> saveWorkPhone(HttpServletRequest request, MultipartFile file) {
        int rtn = 0;
        try {
            Long userbookId = Long.valueOf(request.getParameter("id"));
            Long contentId  = Long.valueOf(request.getParameter("contentId"));
            Long qid  = Long.valueOf(request.getParameter("qid"));
            String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).toLowerCase();
            String fileBase64 = Base64Util.getInstance().encode(file.getBytes());
            String txtStr = "";
            String result = ParsePdfContent.OCR(fileBase64, tess4jClient.uploadpath, fileSuffix, "作业"+contentId+"问题"+qid);
            System.out.println("result:"+result);
            List<BookQuestionDto> bookContentDList = this.getContentDList(contentId);
            for (BookQuestionDto obj:bookContentDList) {
                if (obj.getId().equals(qid)) {
                    txtStr = obj.getContent();
                    System.out.println("txtStr:"+txtStr);
                    double d = StrUtil.similar(result, txtStr);
                    System.out.println("test d:"+d);
                    if (d<0.3) {
                        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "请确认拍摄内容！", false);
                    }else {
                        List<UserBookDetailResp> list = userBooksDetailMapper.getBookDetailByBId(userbookId, contentId, qid);
                        if (null!=list&&list.size()>0) {
                            UserBookDetailEntity entity = BeanUtil.copyProperties(list.get(0), UserBookDetailEntity.class);
                            entity.setFileUrl(fileBase64);
                            entity.setJxcontent(result);
                            entity.setCreateTime(SimpleDateFormatUtil.getNowDate());
                            if (d>0.8) {
                                entity.setStatus("1");
                            }else {
                                entity.setStatus("0");
                            }
                            rtn = userBooksDetailMapper.updateById(entity);
                        }else {
                            UserBookDetailEntity entity = new UserBookDetailEntity();
                            entity.setUserbookId(userbookId);
                            entity.setContentId(contentId);
                            entity.setContentdId(qid);
                            entity.setFileUrl(fileBase64);
                            entity.setJxcontent(result);
                            entity.setCreateTime(SimpleDateFormatUtil.getNowDate());
                            if (d>0.8) {
                                entity.setStatus("1");
                            }else {
                                entity.setStatus("0");
                            }
                            rtn = userBooksDetailMapper.insert(entity);
                        }
                    }
                    break;
                }
            }
        }catch (IOException ioe) {
            ioe.printStackTrace();
        }
        if (rtn>0) {
            return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "保存成功", true);
        }else {
            return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "保存失败", false);
        }
    }

    @Override
    public NftResponse<Paginator<BookResp>> getBookInfos(Long userId, Integer pageNo, Integer pageSize) {
        Paginator<BookResp> paginator = new Paginator<BookResp>(pageNo, pageSize, 0, new ArrayList<>());
        IPage<BookResp> resultPage = userBooksMapper.getBookInfoPageByUserId(new Page<>(pageNo,pageSize),userId);
        List<BookResp> pageResult = BeanUtil.copyToList(resultPage.getRecords(), BookResp.class);
        for (BookResp obj:pageResult) {
            List<BookContentResp> bookContentList = this.getContentList(obj.getId());
            if (null!=bookContentList) {
                BookContentResp contentResp = bookContentList.get(0);
                obj.setBookCover("http://timeadmin.shudingkj.com/prod-api"+contentResp.getFileUrl());
            }
        }
        paginator.setPageNo(resultPage.getCurrent());
        paginator.setPageSize(resultPage.getSize());
        paginator.setTotalDataNum(resultPage.getTotal());
        paginator.setPageData(pageResult);
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "查询成功", paginator);
    }

    @Override
    public NftResponse<Boolean> putBookInfo(UserBookReq query) {
        Long taskId = query.getTaskId();
        Long userId = query.getUserId();
        Map<Object, Object> mapValue = myRedisTemplate.opsForHash().entries("BOOK:DATA:"+taskId);
        UserBookEntity entity = new UserBookEntity();
        if (mapValue.isEmpty()) {
            BookEntity bookInfo = this.baseMapper.selectById(taskId);
            mapValue = new HashMap<>();
            mapValue.put(bookInfo.getId()+"", JSON.toJSONString(bookInfo));
            entity.setTitle(bookInfo.getTitle());
            myRedisTemplate.opsForHash().putAll("BOOK:DATA:"+taskId, mapValue);
        }else {
            for (Map.Entry<Object, Object> entry : mapValue.entrySet()) {
                BookEntity entityBook = JSON.parseObject(entry.getValue().toString(), BookEntity.class);
                entity.setTitle(entityBook.getTitle());
            }
        }
        entity.setTaskId(taskId);
        entity.setUserId(userId);
        entity.setCreateTime(SimpleDateFormatUtil.getNowDate());
        BookResp bookInfo = userBooksMapper.getBookInfosByUserIdAndId(userId, taskId);
        int rtn = 0;
        if (null==bookInfo) {
            rtn = userBooksMapper.insert(entity);
        }
        if (rtn>0) {
            return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "上架成功", true);
        } else {
            return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "已经上架", false);
        }
    }

    @Override
    public NftResponse<List<String>> getClassInfos(Long userId) {
        List<SchoolStudentResp> list = schoolStudentMapper.getClassInfosByUserId(userId);
        List<String> records = new ArrayList<>();
        for (SchoolStudentResp obj:list) {
            records.add(obj.getClassesName());
        }
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "查询成功", records);
    }

    @Override
    public NftResponse<Boolean> putClassInfo(Long userId, Long classId) {
        Map<Object, Object> mapValue = myRedisTemplate.opsForHash().entries("CLASS:DATAB:"+classId);
        SchoolClassesResp classResp = null;
        if (mapValue.isEmpty()) {
            SchoolClassesEntity entity = schoolClassesMapper.selectById(classId);
            mapValue = new HashMap<>();
            mapValue.put(entity.getId()+"", JSON.toJSONString(entity));
            classResp = BeanUtil.copyProperties(entity, SchoolClassesResp.class);
            myRedisTemplate.opsForHash().putAll("CLASS:DATAB:"+classId, mapValue);
        }else {
            for (Map.Entry<Object, Object> entry : mapValue.entrySet()) {
                SchoolClassesEntity entity = JSON.parseObject(entry.getValue().toString(), SchoolClassesEntity.class);
                classResp = BeanUtil.copyProperties(entity, SchoolClassesResp.class);
            }
        }
        SchoolStudentEntity insertEntity = new SchoolStudentEntity();
        insertEntity.setSchoolId(classResp.getSchoolId());
        insertEntity.setClassesId(classId);
        insertEntity.setStudentId(userId);
        insertEntity.setCreateTime(SimpleDateFormatUtil.getNowDate());
        int rtn = schoolStudentMapper.insert(insertEntity);
        if (rtn>0) {
            return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "修改成功", true);
        }else {
            return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "修改失败", false);
        }
    }

    @Override
    public NftResponse<Boolean> putUsername(Long userId, String userName) {
        SysUserEntity sysUserEntity = new SysUserEntity();
        sysUserEntity.setUserId(userId);
        sysUserEntity.setUserName(userName);
        int rtn = sysUserMapper.updateById(sysUserEntity);
        if (rtn>0) {
            return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "修改成功", true);
        }else {
            return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "修改失败", false);
        }
    }

    @Override
    public String putAvatar(HttpServletRequest request, MultipartFile file) {
        String fileBase64 = "";
        try {
            fileBase64 = Base64Util.getInstance().encode(file.getBytes());
            SysUserEntity sysUserEntity = new SysUserEntity();
            sysUserEntity.setUserId(Long.valueOf(request.getParameter("userId")));
            sysUserEntity.setAvatar(fileBase64);
            sysUserMapper.updateById(sysUserEntity);
        }catch (IOException ioe) {}
        return fileBase64;
    }

    @Override
    public Boolean putOpenId(String phonenumber, String openId) {
        QueryWrapper<SysUserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(QueryUtil.camelToUnderline("status"), "0");
        wrapper.eq(QueryUtil.camelToUnderline("delFlag"), "0");
        wrapper.eq(QueryUtil.camelToUnderline("phonenumber"), phonenumber);
        List<SysUserEntity> users = this.sysUserMapper.selectList(wrapper);
        if (null==users||users.size()<=0) {
            SysUserReq sysUserReq = new SysUserReq();
            sysUserReq.setUserName(phonenumber);
            NftResponse registerResult = authService.userMinRegister(sysUserReq);
            SysUserEntity userAppEntity = (SysUserEntity)registerResult.getData();
            userAppEntity.setMinopenId(openId);
            sysUserMapper.updateById(userAppEntity);
            return true;
        }else {
            SysUserEntity user = users.get(0);
            if (!openId.equals(user.getMinopenId())) {
                sysUserMapper.updateUserOpenIdByPhone(phonenumber, openId);
            }
            return true;
        }
    }

    @Override
    public NftResponse<SysUserResp> getUserInfo(String openId) {
        QueryWrapper<SysUserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(QueryUtil.camelToUnderline("status"), "0");
        wrapper.eq(QueryUtil.camelToUnderline("delFlag"), "0");
        wrapper.eq(QueryUtil.camelToUnderline("minopenId"), openId);
        List<SysUserEntity> users = this.sysUserMapper.selectList(wrapper);
        if (users==null||users.size()<=0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "查无此人", null);
        }
        SysUserResp userAppResp = BeanUtil.copyProperties(users.get(0), SysUserResp.class);
        SysUserResp rtn = this.sysUserMapper.getUserStudent(users.get(0).getUserId());
        if (null!=rtn&&null!=rtn.getUserId()) {
            userAppResp.setIsTeacher(true);
        }else {
            userAppResp.setIsTeacher(false);
        }
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "查询成功", userAppResp);
    }

    @Override
    public NftResponse<List<UserBookDetailResp>> getErrorQ(Long taskId, Long userId, String status) {
        List<UserBookDetailResp> list = null;
        if (!"".equals(status)) {
            list = userBooksDetailMapper.getErrorDetailByUserIdStatus(taskId, userId, status);
        }else {
            list = userBooksDetailMapper.getErrorDetailByUserId(taskId, userId);
        }
        List<BookContentResp> bookContentList = this.getContentList(taskId);
        Map<Long,Integer> pageMap = new HashMap<>();
        for (BookContentResp obj:bookContentList) {
            if (null!=obj.getFileUrl()) {
                int index = obj.getFileUrl().indexOf("study-");
                if (index>0) {
                    int indexEnd = obj.getFileUrl().indexOf(".jpg");
                    String pageStr = obj.getFileUrl().substring(index+6,indexEnd);
                    int startPage = Integer.valueOf(pageStr);
                    pageMap.put(obj.getId(),startPage);
                }
            }

        }
        for (UserBookDetailResp obj:list) {
            Integer page = pageMap.get(obj.getContentId());
            obj.setPageNum(page);
            List<BookQuestionDto> bookContentDList = this.getContentDList(obj.getContentId());
            for (BookQuestionDto objQ:bookContentDList) {
                if (null!=obj.getContentdId()&&obj.getContentdId().equals(objQ.getId())) {
                    obj.setQuestionNum(objQ.getQuestionNum());
                    obj.setQfileUrl(objQ.getUrl());
                }
            }
        }
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "查询成功", list);
    }
}
